package com.atung.parking.service.impl;

import com.atung.parking.config.auth.AuthUserMangerContext;
import com.atung.parking.config.result.ApiResult;
import com.atung.parking.config.result.PageInfoResponse;
import com.atung.parking.controller.DateConvertUtil;
import com.atung.parking.entity.BusMessagePublish;
import com.atung.parking.enums.AdminType;
import com.atung.parking.enums.ExportType;
import com.atung.parking.enums.MessageState;
import com.atung.parking.enums.MessageType;
import com.atung.parking.export.MessagePublishExportVO;
import com.atung.parking.export.PublicExportUtil;
import com.atung.parking.mapper.BusMessagePublishMapper;
import com.atung.parking.mapstruct.MessagePublishConverter;
import com.atung.parking.request.query.QueryMessageRequest;
import com.atung.parking.request.save.SaveOrUpdateMessageRequest;
import com.atung.parking.response.page.MessagePublishResponse;
import com.atung.parking.service.MessagePublishService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.time.FastDateFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author Administrator
 */
@Service
public class MessagePublishServiceImpl implements MessagePublishService {

    @Resource
    private BusMessagePublishMapper busMessagePublishMapper;
    @Resource
    private MessagePublishConverter messagePublishConverter;
    @Resource
    private PublicExportUtil publicExportUtil;

    @Override
    public ApiResult saveMessageService(SaveOrUpdateMessageRequest request) {
        //根据状态判断特色自动校验
        try {
            this.validSaveMethod(request);
        } catch (Exception e) {
            return ApiResult.fail(e.getMessage());
        }

        BusMessagePublish busMessagePublish = new BusMessagePublish();
        BeanUtils.copyProperties(request, busMessagePublish);
        busMessagePublish.setMessageType(request.getMessageType().ordinal());
        busMessagePublish.setMessageState(MessageState.NORMAL.getCode());
        busMessagePublishMapper.insert(busMessagePublish);
        return ApiResult.ok();
    }

    @Override
    public PageInfoResponse<BusMessagePublish> superQueryListService(QueryMessageRequest request) {
        QueryWrapper<BusMessagePublish> queryWrapper = createQueryWrapper(request);
        Page<BusMessagePublish> page = new Page<>(request.getPageNum(), request.getPageSize());
        Page<BusMessagePublish> busParkingIotPage = busMessagePublishMapper.selectPage(page, queryWrapper);
        PageInfoResponse<BusMessagePublish> pageResponse = new PageInfoResponse<>();
        pageResponse.setData(busParkingIotPage.getRecords());
        pageResponse.setTotal(busParkingIotPage.getTotal());
        return pageResponse;
    }

    @Override
    public ApiResult updateMessageStateService(Long id) {

        BusMessagePublish busMessagePublish = busMessagePublishMapper.selectById(id);
        if (Objects.isNull(busMessagePublish)) {
            return ApiResult.ok();
        }
        busMessagePublish.setMessageState(MessageState.DELETED.getCode());
        busMessagePublishMapper.updateById(busMessagePublish);
        return ApiResult.ok();
    }

    @Override
    public void exportMessageListService(QueryMessageRequest request, HttpServletResponse httpServletResponse) {
        QueryWrapper<BusMessagePublish> queryWrapper = createQueryWrapper(request);
        List<BusMessagePublish> busMessagePublishList = busMessagePublishMapper.selectList(queryWrapper);
        List<MessagePublishExportVO> collect = busMessagePublishList.stream().map(item -> {
            MessagePublishExportVO messagePublishExportVO = messagePublishConverter.toExportVO(item);
            messagePublishExportVO.setHasChargingPile(item.getHasChargingPile().equals(0) ? "无" : "有");
            FastDateFormat formatter = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");
            // 格式化日期时间
            try {
                String formattedDate = formatter.format(Long.valueOf(item.getCreatorTime()));
                messagePublishExportVO.setCreatorTime(formattedDate);
            } catch (Exception e) {
                messagePublishExportVO.setCreatorTime("时间格式化出现问题");
            }

            return messagePublishExportVO;

        }).collect(Collectors.toList());
        try {
            switch (request.getMessageType()) {
                case RENT_OFFER:
                    publicExportUtil.exportReport(ExportType.RENT_OFFER_EXPORT, collect, httpServletResponse);
                    break;
                case SALE_OFFER:
                    publicExportUtil.exportReport(ExportType.SALE_OFFER_EXPORT, collect, httpServletResponse);
                    break;
                case RENT_REQUEST:
                    publicExportUtil.exportReport(ExportType.RENT_REQUEST_EXPORT, collect, httpServletResponse);
                    break;
                case PURCHASE_REQUEST:
                    publicExportUtil.exportReport(ExportType.PURCHASE_REQUEST_EXPORT, collect, httpServletResponse);
                    break;
                default:
                    return;
            }

        } catch (Exception e) {

        }
    }

    @Override
    public List<MessagePublishResponse> queryOneselfMessageService(MessageType messageType) {
        QueryWrapper<BusMessagePublish> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("message_type", messageType.ordinal());
        queryWrapper.eq("creator_id",String.valueOf(AuthUserMangerContext.getUserId()));
        queryWrapper.orderByDesc("creator_time");
        List<BusMessagePublish> busMessagePublishes = busMessagePublishMapper.selectList( queryWrapper);
       return busMessagePublishes.stream().map(messagePublishConverter::toResponse).collect(Collectors.toList());
    }


    public QueryWrapper<BusMessagePublish> createQueryWrapper(QueryMessageRequest request) {
        QueryWrapper<BusMessagePublish> queryWrapper = new QueryWrapper<>();
        //联系电话
        if (StringUtils.hasText(request.getContactPhone())) {
            queryWrapper.eq("contact_phone", request.getContactPhone());
        }

        //用户编号
        if (StringUtils.hasText(request.getUserId())) {
            queryWrapper.eq("id", request.getUserId());
        }
        //用户名
        if (StringUtils.hasText(request.getContactName())) {
            queryWrapper.eq("contact_name", request.getContactName());
        }
        //是否需要充电桩
        if (Objects.nonNull(request.getHasChargingPile())) {
            queryWrapper.eq("has_charging_pile", request.getHasChargingPile());
        }
        //状态
        if (Objects.nonNull(request.getMessageState())) {
            queryWrapper.eq("message_state", request.getMessageState());
        }
        //时间查询
        if (StringUtils.hasText(request.getStartData()) && StringUtils.hasText(request.getEndData())) {
            Long start = DateConvertUtil.convertQueryStartToMillis(request.getStartData());
            Long end = DateConvertUtil.convertQueryEndToMillis(request.getEndData());
            if (Objects.nonNull(request.getStartData()) && Objects.nonNull(request.getEndData())) {
                queryWrapper.between("creator_time", start, end);
            }

        }
        AdminType roleType = AuthUserMangerContext.getAuthUserEntity().getRoleType();
        if (roleType.equals(AdminType.USER)) {
            queryWrapper.eq("message_state", MessageState.NORMAL.getCode());
        }
        queryWrapper.eq("message_type", request.getMessageType().ordinal());
        queryWrapper.orderByDesc("creator_time");
        return queryWrapper;

    }

    public Boolean validSaveMethod(SaveOrUpdateMessageRequest request) {
        //出租
        if (request.getMessageType().equals(MessageType.RENT_OFFER) ||
                request.getMessageType().equals(MessageType.SALE_OFFER)) {

            if (!StringUtils.hasText(request.getParkingSpaceImage())) {
                throw new RuntimeException("车位图片不能为空");
            }
            if (!StringUtils.hasText(request.getParkingSpaceNumber())) {

                throw new RuntimeException("车位编号不能为空");
            }

        }
        return true;
    }
}
